#!/usr/bin/env python3
"""
工具执行器
"""

import time
import logging
from typing import Dict, Any, Optional, List
from datetime import datetime
from .tool import Tool, ToolResult
from .registry import ToolRegistry

logger = logging.getLogger(__name__)

class ToolExecutor:
    """工具执行器"""
    
    def __init__(self, registry: ToolRegistry):
        self.registry = registry
        self.execution_history: List[Dict[str, Any]] = []
        self.current_execution: Optional[Dict[str, Any]] = None
    
    def execute_tool(self, tool_name: str, parameters: Dict[str, Any], 
                    context: Dict[str, Any] = None) -> ToolResult:
        """执行工具"""
        start_time = time.time()
        
        try:
            # 获取工具
            tool = self.registry.get_tool(tool_name)
            if not tool:
                return ToolResult(
                    success=False,
                    error=f"工具不存在: {tool_name}",
                    execution_time=time.time() - start_time
                )
            
            # 检查工具是否启用
            metadata = self.registry.tool_metadata.get(tool_name, {})
            if not metadata.get("enabled", True):
                return ToolResult(
                    success=False,
                    error=f"工具已禁用: {tool_name}",
                    execution_time=time.time() - start_time
                )
            
            # 验证参数
            if not tool.validate_parameters(parameters):
                return ToolResult(
                    success=False,
                    error=f"参数验证失败: {tool_name}",
                    execution_time=time.time() - start_time
                )
            
            # 记录执行开始
            execution_id = f"exec_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
            self.current_execution = {
                "execution_id": execution_id,
                "tool_name": tool_name,
                "parameters": parameters,
                "context": context,
                "start_time": datetime.now(),
                "status": "running"
            }
            
            # 执行工具
            logger.info(f"执行工具: {tool_name}, 参数: {parameters}")
            result = tool.execute(**parameters)
            
            # 更新工具使用统计
            tool.update_usage()
            
            # 记录执行结果
            end_time = time.time()
            execution_time = end_time - start_time
            
            self.current_execution.update({
                "end_time": datetime.now(),
                "status": "completed",
                "result": result.to_dict(),
                "execution_time": execution_time
            })
            
            # 保存到执行历史
            self.execution_history.append(self.current_execution.copy())
            
            # 添加执行元数据
            result.metadata = result.metadata or {}
            result.metadata.update({
                "execution_id": execution_id,
                "tool_name": tool_name,
                "execution_time": execution_time,
                "timestamp": datetime.now().isoformat()
            })
            
            return result
            
        except Exception as e:
            # 记录执行错误
            end_time = time.time()
            execution_time = end_time - start_time
            
            if self.current_execution:
                self.current_execution.update({
                    "end_time": datetime.now(),
                    "status": "failed",
                    "error": str(e),
                    "execution_time": execution_time
                })
                self.execution_history.append(self.current_execution.copy())
            
            logger.error(f"工具执行失败: {tool_name}, 错误: {e}")
            
            return ToolResult(
                success=False,
                error=str(e),
                execution_time=execution_time,
                metadata={
                    "execution_id": execution_id if 'execution_id' in locals() else None,
                    "tool_name": tool_name,
                    "timestamp": datetime.now().isoformat()
                }
            )
    
    def execute_tool_chain(self, tool_chain: List[Dict[str, Any]], 
                          context: Dict[str, Any] = None) -> List[ToolResult]:
        """执行工具链"""
        results = []
        current_context = context or {}
        
        for i, tool_call in enumerate(tool_chain):
            tool_name = tool_call.get("tool_name")
            parameters = tool_call.get("parameters", {})
            
            # 将前一个工具的结果作为下一个工具的输入
            if i > 0 and results:
                previous_result = results[-1]
                if previous_result.success:
                    # 根据工具类型传递不同的参数
                    if tool_name == "count_errors" and "parsed_logs" in previous_result.data:
                        parameters["parsed_logs"] = previous_result.data["parsed_logs"]
                    elif tool_name == "analyze_time_patterns" and "parsed_logs" in previous_result.data:
                        parameters["parsed_logs"] = previous_result.data["parsed_logs"]
                    else:
                        parameters["previous_result"] = previous_result.data
                    
                    current_context["previous_results"] = [r.to_dict() for r in results]
            
            # 执行工具
            result = self.execute_tool(tool_name, parameters, current_context)
            results.append(result)
            
            # 如果工具执行失败，可以选择继续或停止
            if not result.success and tool_call.get("required", True):
                logger.warning(f"必需工具执行失败: {tool_name}, 停止工具链")
                break
        
        return results
    
    def get_execution_history(self) -> List[Dict[str, Any]]:
        """获取执行历史"""
        return self.execution_history.copy()
    
    def get_tool_usage_stats(self) -> Dict[str, Any]:
        """获取工具使用统计"""
        stats = {}
        
        for execution in self.execution_history:
            tool_name = execution["tool_name"]
            if tool_name not in stats:
                stats[tool_name] = {
                    "total_executions": 0,
                    "successful_executions": 0,
                    "failed_executions": 0,
                    "total_execution_time": 0.0,
                    "average_execution_time": 0.0
                }
            
            stats[tool_name]["total_executions"] += 1
            if execution["status"] == "completed":
                stats[tool_name]["successful_executions"] += 1
            else:
                stats[tool_name]["failed_executions"] += 1
            
            if "execution_time" in execution:
                stats[tool_name]["total_execution_time"] += execution["execution_time"]
        
        # 计算平均执行时间
        for tool_name, stat in stats.items():
            if stat["total_executions"] > 0:
                stat["average_execution_time"] = stat["total_execution_time"] / stat["total_executions"]
        
        return stats
    
    def clear_history(self):
        """清空执行历史"""
        self.execution_history = []
        self.current_execution = None
